<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useMockStore } from '../store/mockStore'
import httpClient from '../utils/http'
import { ElMessage } from 'element-plus'

const router = useRouter()
const mockStore = useMockStore()

const mocks = ref([])

// 获取接口列表
const fetchMocks = async () => {
  try {
    const response = await httpClient.get('/v1/mocs')
    console.log('API响应:', response)
    
    // 根据API定义，数据在response.data.data中
    if (response.data && response.data.data) {
      mocks.value = response.data.data.map((item: any) => ({
        id: item.id,
        name: item.name,
        url: item.url,
        method: item.method
      }))
    } else {
      console.warn('响应数据格式不正确:', response.data)
      mocks.value = []
    }
  } catch (error: any) {
    console.error('获取接口列表失败:', error)
    console.error('错误详情:', error.response?.data || error.message)
  }
}

onMounted(() => {
  fetchMocks()
})

const viewMock = (id: string) => {
  router.push(`/mock/${id}`)
}

const editMock = (id: string) => {
  router.push(`/edit/${id}`)
}

const deleteMock = async (id: string) => {
  // 添加确认提示
  const confirmDelete = window.confirm('确定要删除吗？')
  
  if (confirmDelete) {
    try {
      // 调用删除接口
      const response = await httpClient.delete(`/v1/mocs/${id}`)
      
      // 检查响应
      if (response.data && response.data.success) {
        console.log('删除成功:', response.data.msg)
        ElMessage.success('删除接口成功')
        
        // 重新获取列表数据
        fetchMocks()
      } else {
        const errorMsg = response.data?.msg || '未知错误'
        const errorCode = response.data?.code || response.status || '未知状态码'
        console.error('删除失败:', errorMsg)
        alert(`删除失败: ${errorMsg} (错误代码: ${errorCode})`)
      }
    } catch (error: any) {
      // 处理网络错误或其他异常
      console.error('删除接口失败:', error)
      
      // 检查是否有响应数据（如500错误）
      if (error.response) {
        const errorMsg = error.response.data?.msg || error.response.statusText || '服务器错误'
        const errorCode = error.response.data?.code || error.response.status || '未知状态码'
        alert(`删除失败: ${errorMsg} (错误代码: ${errorCode})`)
      } else {
        // 网络错误或服务器无响应
        alert('删除接口失败: 网络错误或服务器无响应')
      }
    }
  }
}
</script>

<template>
  <div class="mock-list">
    <h1>Mock 接口列表</h1>
    <el-table :data="mocks" style="width: 100%" table-layout="auto">
      <el-table-column prop="id" label="ID" min-width="100" />
      <el-table-column prop="name" label="接口名称" min-width="150" />
      <el-table-column prop="url" label="URL" min-width="180" />
      <el-table-column prop="method" label="方法" min-width="100" />
      <el-table-column label="操作" min-width="200">
        <template #default="scope">
          <el-button size="small" @click="viewMock(scope.row.id)">查看</el-button>
          <el-button size="small" @click="editMock(scope.row.id)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteMock(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<style scoped>
.mock-list {
  padding: 20px;
}

/* 优化表格样式，实现自适应布局 */
.mock-list :deep(.el-table) {
  width: 100%;
}

.mock-list :deep(.el-table__header th) {
  height: 50px;
}

.mock-list :deep(.el-table__body td) {
  height: 40px;
}

/* 设置表格列的最小宽度，防止内容被过度压缩 */
.mock-list :deep(.el-table__header th:nth-child(1)),
.mock-list :deep(.el-table__body td:nth-child(1)) {
  min-width: 150px;
}

.mock-list :deep(.el-table__header th:nth-child(2)),
.mock-list :deep(.el-table__body td:nth-child(2)) {
  min-width: 180px;
}

.mock-list :deep(.el-table__header th:nth-child(3)),
.mock-list :deep(.el-table__body td:nth-child(3)) {
  min-width: 100px;
}

.mock-list :deep(.el-table__header th:nth-child(4)),
.mock-list :deep(.el-table__body td:nth-child(4)) {
  min-width: 200px;
}
</style>